Ext.onReady(function() {
	var condition = Ext.Object.fromQueryString(location.search);
	var loadMask = new Ext.LoadMask(Ext.getBody(), {msg:"请稍后, 后台正在处理..."});
	var canNew = true;
	var backBtn = {
		text : '返回',
		xtype : 'button',
		listeners : {
			click : function() {
				if(!Ext.isEmpty(condition)){
					if(condition.type == 1){
						location.href = "/work/detail/" + condition.workid;
					}
					else{
						location.href = "/wuziMgr/wz_ly";
					}
				}
				else{
					location.href = "/wuziMgr/wz_ly";
				}
			}
		}
	};
	var saveBtn = {
		text : '保存',
		xtype : 'button',
		listeners : {
			click : function() {
				var grid = Ext.getCmp("orders");
				var store = grid.getStore();
				var models = store.getRange(0, store.getCount());
				var Orders = [];
				for (var i = 0; i < models.length; i++) {
					Ext.Array.include(Orders, {
								DeviceId : models[i].get("DeviceId"),
								Count : models[i].get("Count")
							});
				}
				var jsonData = {
					Id : deviceRecipient.Id,
					DepartmentId : Ext.getCmp("Department").getValue(),
					GroupId : Ext.getCmp("Flight").getValue(),
					UserId : Ext.getCmp("User").getValue(),
					Time : Ext.Date.format(Ext.getCmp("Time").getValue(),
							"Y-m-d H:i:s"),
					Desp : Ext.getCmp("Desp").getValue(),
					Orders : Orders
				}
				Ext.Ajax.request({
							url : "/device_recipient/update",
							type : "POST",
							jsonData : jsonData,
							callback : function(options, success, response) {
								if (success) {
									var result = Ext
											.decode(response.responseText);
									if (result.success) {
										location.href = "/wuziMgr/wz_ly";
									} else {
										Ext.Msg.alert("错误", result.msg);

									}
								}
							}
						})
			}
		}
	};
	var exportBtn = {
		text : '导出',
		xtype : 'button',
		listeners : {
			click : function() {
				window.open('/device_recipient/export/'+deviceRecipient.Id + '?time='+new Date().getTime());
			}
		}
	};
	var toolbar = Ext.create('Ext.toolbar.Toolbar', {
				dock : 'top',
				items : []
			});
	Ext.Ajax.request({
						url : 'privilege/has_privilege',
						params : {
							action : '/device_recipient/add'
						},
						async: false,
						callback : function(options, success, response) {
							if (success) {
								try {
									var ar = Ext.decode(response.responseText);
									canNew = ar.data;
								} catch (e) {
									canNew = false;
								}
							} else {
								canNew = false;
							}
							toolbar.add(backBtn);
							if (canNew) {
								toolbar.add(saveBtn);
							}
							toolbar.add(exportBtn);
						}
					});
	var departmentStore = Ext.create('Ext.data.Store', {
				fields : [{
							name : 'Id',
							type : 'int'
						}, 'Name'],
				proxy : {
					type : 'ajax',
					url : '/department/all',
					reader : {
						type : 'json',
						root : 'data.rows'
					}
				},
				autoLoad : true
			});

	var department = Ext.create('Ext.form.ComboBox', {
				fieldLabel : '部门',
				labelWidth : 60,
				width : 200,
				editable : false,
				id : 'Department',
				store : departmentStore,
				queryMode : 'local',
				displayField : 'Name',
				valueField : 'Id',
				value : deviceRecipient.Department.Id
			});

	var flightStore = Ext.create('Ext.data.Store', {
				fields : ["Id", 'Name'],
				proxy : {
					type : 'ajax',
					url : '/flight/all',
					reader : {
						type : 'json',
						root : 'data.rows'
					}
				},
				autoLoad : true
			});

	var flight = Ext.create('Ext.form.ComboBox', {
				fieldLabel : '班组',
				labelWidth : 60,
				width : 200,
				editable : false,
				id : 'Flight',
				store : flightStore,
				queryMode : 'local',
				displayField : 'Name',
				valueField : 'Id',
				value : deviceRecipient.Group.Id,
				listeners: {
					change: function(self, newValue, oldValue){
						var dptId = department.getValue();
						userStore.proxy.url = '/user/find_by_dept_flight/' + dptId + '/' + newValue;
						userStore.reload();
					}
				}
			});
	var userStore = Ext.create('Ext.data.Store', {
				fields : ["Id", "Username", 'Name'],
				proxy : {
					type : 'ajax',
					url : '/user/all',
					reader : {
						type : 'json',
						root : 'data.rows'
					}
				},
				autoLoad : true
			});
	var recipientor = Ext.create("Ext.form.ComboBox", {
				fieldLabel : '领用人',
				labelWidth : 60,
				width : 200,
				id : 'User',
				editable : false,
				store : userStore,
				queryMode : 'local',
				valueField : 'Id',
				value : deviceRecipient.Recipients.Id,
				tpl : Ext
						.create(
								'Ext.XTemplate',
								'<tpl for=".">',
								'<div class="x-boundlist-item">{Username}({Name})</div>',
								'</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">',
						'{Username}({Name})', '</tpl>')
			});

	var deviceStore = Ext.create('Ext.data.Store', {
				fields : ['Id', {
							name : "Type",
							type : "object"
						}, "Model"],
				proxy : {
					type : 'ajax',
					url : '/device/distinct',
					reader : {
						type : 'json',
						root : 'data.rows'
					}
				},
				autoLoad : true
			});

	var device = Ext.create('Ext.form.ComboBox', {
				id : "device",
				labelWidth : 60,
				width : 200,
				fieldLabel : '设备类型',
				store : deviceStore,
				allowBlank : false,
				editable : false,
				queryMode : 'local',
				valueField : 'Id',
				tpl : Ext
						.create(
								'Ext.XTemplate',
								'<tpl for=".">',
								'<div class="x-boundlist-item">{Type.Name}({Model})</div>',
								'</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">',
						'{Type.Name}({Model})', '</tpl>'),
				listeners:{
					change: function(self, newValue, oldValue){
						loadMask.show();
						Ext.Ajax.request({
							url: '/device/available',
							params:{
								id: newValue
							},
							callback: function(options, success, response){
								loadMask.hide();
								if(success){
									var ar = Ext.decode(response.responseText);
									if(ar.success){
										Ext.getCmp("Count").setMaxValue(ar.data);
									}
								}
							}
						})
					}
				}
			});
	var addPanel1 = Ext.create('Ext.toolbar.Toolbar', {
				dock : 'top',
				border : false,
				items : [department, flight, recipientor]
			});
	var addPanel2 = Ext.create('Ext.form.Panel', {
				dock : 'top',
				layout : 'hbox',
				margin : '0 10',
				border : false,
				items : [device, {
							xtype : 'numberfield',
							id : "Count",
							labelWidth : 60,
							allowBlank : false,
							margin : '0 5',
							width : 200,
							maxValue:1,
							minValue : 1,
							fieldLabel : '数量'
						}, {
							xtype : "button",
							margin : '0 5',
							text : "加入",
							listeners : {
								click : function() {
									if (!addPanel2.isValid()) {
										return;
									}
									var store = device.getStore();
									var deviceId = device.getValue()
									var record = store.findRecord("Id",
											deviceId);
									var grid = Ext.getCmp("orders");
									var gridStore = grid.getStore();

									var tmp = gridStore.findRecord("DeviceId",
											deviceId);
									if (tmp != null) {
										tmp.set("Count", tmp.get("Count")
														+ Ext.getCmp("Count")
																.getValue());
										gridStore.commitChanges();
									} else {
										gridStore.add({
													DeviceId : deviceId,
													Name : record.get("Type").Name,
													Model : record.get("Model"),
													Count : Ext.getCmp("Count")
															.getValue()
												});
									}
								}
							}
						}]
			});

	var store = Ext.create('Ext.data.Store', {
				fields : ["DeviceId", "Name", "Model", "Count"]
			});
	if (!Ext.isEmpty(deviceRecipient.RecipientOrders)) {
		for (var i = 0; i < deviceRecipient.RecipientOrders.length; i++) {
			var tmp = deviceRecipient.RecipientOrders[i];
			store.add({
						DeviceId : tmp.Device.Id,
						Name : tmp.Device.Type.Name,
						Model : tmp.Device.Model,
						Count : tmp.Count
					});
		}
	}
	var grid = Ext.create('Ext.grid.Panel', {
				id : "orders",
				minHeight : 100,
				store : store,
				margin : '5 10',
				columns : [{
							text : '序号',
							xtype : 'rownumberer',
							width : 40,
							sortable : false
						}, {
							text : '设备类型',
							flex : 1,
							renderer: function(v, meta, record){
								return record.get('Name') + '(' + record.get('Model') + ')';
							}
						}, {
							text : '数量',
							dataIndex : 'Count'
						}, {
							text : '操作',
							xtype : 'actioncolumn',
							width : 50,
							items : [{
										icon : 'view/images/delete.png',
										tooltip : 'Delete',
										handler : function(grid, rowIndex,
												colIndex) {
											grid.getStore().removeAt(rowIndex);
										}
									}]
						}]
			});
	var dockedItems = [];
	if(canNew){
		dockedItems = [toolbar, addPanel1, addPanel2];
	}
	else{
		dockedItems = [toolbar, addPanel1];
	}
	var panel = Ext.create("Ext.panel.Panel", {
				title : '',
				autoScroll : true,
				border : false,
				bodyBorder : false,
				dockedItems: dockedItems,
				items : [grid, {
							xtype : 'label',
							text : '用途说明',
							margin : "0 0 0 10"
						}, {
							xtype : 'textareafield',
							id : "Desp",
							value : deviceRecipient.Desp,
							width : '90%',
							margin : '5 10',
							grow : true
						}, {
							xtype : 'datefield',
							id : "Time",
							labelWidth : 60,
							width : 250,
							margin : '5 10',
							fieldLabel : '领用时间',
							format : 'Y-m-d H:i:s',
							value : deviceRecipient.Time
						}]
			});
	Ext.create('Ext.Viewport', {
				layout : 'fit',
				style : 'background:none;background-color:white;',
				items : [panel]
			});
});